<template>
  <div class="page-containter">
    <uni-nav-bar fixed shadow :border="false" :title="'【问卷】'  + (detail && detail.name || '')" left-icon="left" @clickLeft="onClickLeft"></uni-nav-bar>
    <div class="page-content isWap" v-if="detail">
      <div class="page-bg">
        <div class="page-title fs-24 common-wrap">{{ detail.name }}</div>
        <div class="page-subtitle fs-14 common-wrap">{{ detail.brief }}</div>
      </div>
      <div class="common-wrap content-wrap">
        <div class="test-item" v-for="(item,index) in listData" :key="index">
          <exam
              :testItem="item"
              :testIndex="item.index"
              :showIndex="getShowIndex(listData, item)"
              :optionsList="answer[item.questionsId].options"
              :val="answer[item.questionsId].val"
              :extendAnswer="answer[item.questionsId].extendAnswer"
              :customAnswer="answer[item.questionsId].customAnswer"
              :edit="true"
              :isMustAnswer="detail.isAllAnswer === '1'"
              @openLink="openLink"></exam>
        </div>
        <div class="btn-wrap flex-wrap flex-middle flex-center">
          <button
              round
              class="btn"
              type="primary"
              @click="setPage(pageAll.current - 1, true)"
              v-if="pageAll && pageAll.current > 1">上一页
          </button>
          <button
              round
              class="btn"
              type="primary"
              @click="setPage(pageAll.current + 1, true)"
              v-if="pageAll && pageAll.current < pageAll.total">下一页
          </button>
        </div>
      </div>
    </div>
    <van-action-sheet v-model="actionShow" title="查看跳转">
      <iframe :src="actionURL" id="iframepage" name="iframepage" frameBorder=0 width="100%"
              style="height: 80vh;"></iframe>
    </van-action-sheet>
  </div>
</template>
<script>
import exam from '@/view/questionnaire/exam.vue'
import {parse, stringify, copyBasic, deepClone, getFormTime, getCurrentTime} from '@/assets/js/util.js'
import VanActionSheet from "@/components/vant/van-action-sheet/van-action-sheet.vue";

export default {

  head() {
    return {
      title: this.detail && this.detail.name
    }
  },
  data() {
    return {
      detail: null,
      source: '',
      id: '',
      recordId: '',
      saveLoading: false,
      btnStatus: false,
      currentTime: 0,
      time: 0,
      listAll: [],
      pageAll: null,
      answer: {},
      form: {
        pwd: '',
      },
      showDialog: false,
      rules: {
        pwd: [
          {required: true, message: '请输入验证码', trigger: ['change', 'blur']}
        ]
      },
      actionShow: false,
      actionURL: ''
    }
  },
  onLoad(query) {
    this.id = query.surveyId || ''
    this.recordId = query.id || ''
    this.source = query.source || ''
  },
  mounted() {
    this.getInfo()
  },
  components: {
    VanActionSheet,
    exam
  },
  computed: {
    listData() {
      if (!this.pageAll) {
        return this.listAll
      }
      return this.getPageData(this.listAll, this.pageAll)
    },
    percentage() {
      let arr = 0
      let len = 0
      for (let i in this.answer) {
        if (this.answer[i].type !== 'remark' && this.answer[i].type !== 'partition')
          arr++
        if (this.answer[i].flag) {
          len++
        }
      }
      return Math.ceil(len / arr * 100)
    },
  },
  methods: {
    onClickLeft() {
      uni.navigateBack({delta: 1})
    },
    getShowIndex(list, item) {
      let arr = list.filter(e => e.questionsType !== 'remark' && e.questionsType !== 'partition')
      return arr.findIndex(e => e === item)
    },
    getInfo(code, done) {
      let params = {
        surveyDevice: 1,
        surveyId: this.id,
        recordId: this.recordId,
      }
      this.$api.questionnaire.userReview(params).then(res => {
        let data
        this.detail = res
        this.time = res.autoSaveTime * 60
        data = this.setIndex(res.dataJSON)
        this.listAll = data.list
        this.pageAll = data.page
        this.answer = data.answer
        uni.setNavigationBarTitle({
          title: this.detail.name
        })
      }).catch(e => {
        this.fullscreenLoading = false
        if (e.msg === '该问卷禁止回顾! ' || e.msg === '该问卷禁止回顾!') {
          this.$dialog.alert({
            title: '提示',
            message: e.msg,
            confirmButtonColor: 'var(--color)',
            beforeClose: (action, done) => {
              done()
              this.$uniRedirectTo({
                name: 'questionnaire-start-id',
                params: {
                  id: this.id
                }
              })
            }
          })
        } else {
          this.toast.fail(e.msg)
        }
      })
    },
    // 获取当前分页数据
    getPageData(list, page, type) {
      let start = (page.current - 1) * page.size
      let end = page.current * page.size - 1
      return list.filter((question, i) => i >= start && i <= end)
    },
    // 处理移动
    handleMove(id) {
      let index, page
      if (!this.pageAll || !this.detail.showQuestionsNumPerPage) {
        this.startMove(id)
        return
      }
      index = parseInt((id).replace('child', '')) + 1
      page = Math.ceil(index / this.detail.showQuestionsNumPerPage)
      if (this.pageAll.current !== page) {
        this.setPage(page)
        this.$nextTick(() => {
          this.startMove(id)
        })
      } else {
        this.startMove(id)
      }
    },
    // 开始移动
    startMove(id) {
      document.querySelector(`#${id}`).scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "center"
      })
    },
    setPage(page, status) {
      if (page > 0 && page <= this.pageAll.total) {
        this.$set(this.pageAll, 'current', page)
      }
      if (status) {
        this.$nextTick(() => {
          this.startMove('percentage')
        })
      }
    },
    // 整理问题、问题右侧列表、答案列表
    setIndex(list) {
      let arr = []
      let answer = {}
      let page = null
      let pageSize = this.detail.showQuestionsNumPerPage
      if (list.length) {
        arr = list.map((item, ind) => {
          item.index = ind
          answer[item.questionsId] = {
            type: item.questionsType,
            must: item.isMustAnswer,
            flag: item.questionsRecords && item.questionsRecords.answerFlag === '1',
            index: ind,
            location: 'child' + ind,
            extendAnswer: item.questionsRecords && item.questionsRecords.extendAnswerContentJson ? this.setExtend(parse(item.questionsRecords.extendAnswerContentJson), item.questionsRecords.answerOptionsId) : '',
            customAnswer: item.questionsRecords && item.questionsRecords.customAnswerContentJson ? this.setCustom(parse(item.questionsRecords.customAnswerContentJson), item.questionsRecords.answerOptionsId) : '',
            val: this.setVal(item.questionsType, (item.questionsRecords && item.questionsRecords.answerOptionsId) || (item.questionsRecords && item.questionsRecords.answerContent) || '')
          }
          if (item.questionsType === 'radio' && item.optionsContent && item.optionsContent.length) {
            let arr = []
            item.optionsContent.forEach(it => {
              arr[it.optionsId] = it
            })
            answer[item.questionsId].options = arr
          }
          if (item.questionsType === 'input' && item.content) {
            let reg = /\[\[\*\]\]/ig
            let arr = item.content.match(reg)
            item.optionsContent = arr ? arr.length : 0
          }
          if (item.remark) {
            item.remark = parse(item.remark)
          }
          return item
        })
        if (pageSize) {
          page = {
            size: pageSize,
            current: 1,
            total: Math.ceil(list.length / pageSize)
          }
        }
      }
      return {
        list: arr,
        page: page,
        answer: answer
      }
    },
    setExtend(list, id) {
      let current = list.find(e => e[id])
      return current ? current[id] : ''
    },
    setCustom(list, ids) {
      let current,
          currentKey
      ids = ids.split(',')
      ids.forEach(item => {
        let key = item
        if (list.find(e => e[item])) {
          current = list.find(e => e[item])
          currentKey = key
        }
      })
      return current ? current[currentKey] : ''
    },
    setVal(type, val) {
      if (type === 'check' || type === 'vote') {
        return val ? val.split(',') : []
      } else if (type === 'inputs') {
        return val ? parse(val) : []
      } else if (type === 'input') {
        val = val ? parse(val) : []
        if (typeof val === 'string') {
          val = [val]
        }
        return val
      }
      return val
    },
    openLink(url) {
      this.actionURL = url
      this.actionShow = true
    },
  }
}
</script>
<style lang="scss" scoped>
.page-containter {
  .nav-bar-btn {
    white-space: nowrap;
    width: 60px;
    height: 28px;
  }

  .page-content {
    position: relative;
    z-index: 2;

    .page-bg {
      //position: fixed;
      //z-index: -1;
      width: 100%;
      height: auto;
      background: linear-gradient(318deg, var(--colorl) 0%, var(--color) 100%);
    }

    &.isWap {
      .common-wrap {
        width: 100%;

        &.content-wrap {
          padding: 20px;
        }
      }
    }
  }

  .progress-wrap {
    position: fixed;
    top: 45px;
    left: 0;
    width: 100%;
    border-bottom: 1px solid #EEEEEE;
    z-index: 10;
  }

  .page-title {
    padding: 40px 0 0;
    line-height: 30px;
    color: #fff;
    text-align: center;
  }

  .page-subtitle {
    padding: 15px 0 30px;
    line-height: 24px;
    color: #fff;
    text-align: center;
  }

  .common-wrap {
    width: 100%;
    margin: 0 auto;

    &.content-wrap {
      position: relative;
      padding: 65px 120px 60px;
      background: #FFFFFF;

      .btn-wrap {
        width: 100%;
        padding: 20px 0;
        text-align: center;

        button {
          width: 120px;

          & + button {
            margin-left: 20px;
          }
        }
      }
    }
  }
}
</style>
